<template>
  <div v-if="currentDevice.devices && currentDevice.devices.length > 0">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <b class="header-title">喷头控制</b>
        <el-button-group style="float: right">
          <!-- <el-button type="primary" icon="el-icon-refresh" size="mini" @click="restart">重启设备</el-button> -->
          <el-button
            :disabled="childSelected.length === 0"
            icon="el-icon-s-operation"
            size="mini"
            type="primary"
            @click="showControlAll"
          >
            控制选中
          </el-button>
        </el-button-group>
      </div>
      <el-collapse v-model="activeNames">
        <el-collapse-item
          v-for="(item, index) in currentDevice.steps"
          :key="index"
          :name="index"
        >
          <template slot="title">
            <div class="collapse-title d-flex align-items-center">
              <b style="min-width: 48px; margin-right: 12px">{{ item.name }}</b>
              <el-badge
                v-for="(citem, cindex) in item.devices"
                :key="cindex"
                class="item"
                is-dot
                style="margin: 0 1px"
                :type="getValveClass(citem.rtu_serialno, citem.port)"
              />
              <div class="mlauto pr12">
                <span v-if="getSelectedValves(item) > 0" class="mr12">
                  已选中：
                  <b>{{ getSelectedValves(item) }}</b>
                </span>
                <el-button-group>
                  <el-button
                    icon="el-icon-check"
                    plain
                    size="mini"
                    type="primary"
                    @click.stop="selectAll(item)"
                  >
                    全选
                  </el-button>
                  <el-button
                    icon="el-icon-close"
                    plain
                    size="mini"
                    type="default"
                    @click.stop="cancelAll(item)"
                  >
                    反选
                  </el-button>
                </el-button-group>
              </div>
            </div>
          </template>
          <div class="childs-container">
            <dl
              v-for="(citem, cindex) in item.devices"
              :key="cindex"
              class="menux"
              @click="showControl(citem)"
            >
              <dt>
                <img
                  alt=""
                  :src="getDeviceImage(citem.rtu_serialno, citem.port)"
                />
              </dt>
              <dd>{{ citem.name }}</dd>
              <dd>{{ getPwmInfos(citem.rtu_serialno, citem.port) }}</dd>
              <dd
                v-if="childSelected.includes(citem)"
                class="iconfont icon-active"
              />
            </dl>
          </div>
        </el-collapse-item>
      </el-collapse>
      <el-dialog
        v-drag
        :append-to-body="true"
        destroy-on-close
        title="喷头控制"
        :visible.sync="dialogVisible"
        width="600px"
      >
        <div class="tags">
          <el-tag
            v-for="(item, index) in childSelected"
            :key="index"
            closable
            style="margin: 8px 8px 8px 0"
            type="primary"
            @close="closeTag(index)"
          >
            {{ item.name }}
          </el-tag>
        </div>
        <div class="h20" />
        <el-form
          ref="form"
          label-suffix="："
          label-width="100px"
          :model="formData"
          :rules="rules"
        >
          <el-form-item label="启闭设定" prop="cycle">
            <el-radio-group v-model="actionType" @change="changeActionType">
              <el-radio :label="1">打开</el-radio>
              <el-radio :label="0">关闭</el-radio>
              <el-radio :label="2">占空比</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item label="脉冲周期" prop="cycle">
                <el-input v-model="formData.cycle" placeholder="脉冲周期">
                  <template slot="append">秒</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="占空比" prop="PWM">
                <el-input v-model="formData.PWM" placeholder="占空比">
                  <template slot="append">%</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item>
            <el-button
              icon="el-icon-check"
              type="primary"
              @click="pwmValve('form')"
            >
              提交
            </el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { sendPWM, sendCommand } from '@/api/device'
  import { selectable } from '@/utils/selectable'
  import { uniqueArr, convertArr2Obj } from '@/utils'
  import { resourceBaseUrl } from '@/utils/constant'
  export default {
    data() {
      return {
        activeName: 'first',
        activeNames: ['1'],
        actionType: 2,
        formData: {
          cycle: 60,
          PWM: 60,
          type: 'valves',
          valves: [],
        },
        dialogVisible: false,
        childSelected: [],
        rules: {
          cycle: [
            { required: true, message: '请输入脉冲周期', trigger: 'blur' },
          ],
          PWM: [{ required: true, message: '请输入占空比', trigger: 'blur' }],
        },
        devicesObj: {},
      }
    },
    computed: {
      ...mapGetters(['currentDevice', 'devices']),
    },
    watch: {
      currentDevice: {
        handler(newVal) {
          this.$nextTick(() => {
            selectable('childs-container', 'menux', (list, dom) => {
              list.forEach((item) => {
                this.childSelected.push(newVal.steps[dom].devices[item])
              })
              this.childSelected = uniqueArr(this.childSelected)
            })
          })
        },
        deep: true,
        immediate: true,
      },
      devices: {
        handler(newVal) {
          this.devicesObj = convertArr2Obj(newVal, 'serialno')
        },
        deep: true,
        immediate: true,
      },
    },
    methods: {
      changeActionType(val) {
        const map = {
          1: 100,
          0: 0,
          2: 60,
        }
        this.formData.cycle = 60
        this.formData.PWM = map[val]
      },
      showControl(item) {
        if (!this.childSelected.includes(item)) {
          this.childSelected.push(item)
        } else {
          this.childSelected.splice(
            this.childSelected.findIndex((val) => {
              return val === item
            }),
            1
          )
        }
        this.childSelected = uniqueArr(this.childSelected)
      },
      showControlAll() {
        this.dialogVisible = true
      },
      closeTag(index) {
        this.childSelected.splice(index, 1)
      },
      pwmValve(formName) {
        this.formData.valves = []
        this.$refs[formName].validate((valid) => {
          if (valid) {
            for (const nozzle of this.childSelected) {
              this.formData.valves.push(nozzle)
            }
            this.$confirm('确定要进行此操作吗？', '操作确认', {
              type: 'warning',
            }).then(() => {
              sendPWM(this.formData).then((res) => {
                this.$message({
                  message: res.msg,
                  type: 'success',
                  showClose: true,
                })
              })
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      refresh(cell) {
        const actions = [
          { namekey: 'READ_ALL_AIS', params: true },
          { namekey: 'READ_ALL_HOLDS', params: true },
        ]

        this.$confirm('确定要进行此操作吗？', '操作确认', {
          type: 'warning',
        }).then(() => {
          const rtu_devices = uniqueArr(
            cell.devices.map((val) => {
              return val.rtu_serialno
            })
          )
          let count = 0
          rtu_devices.forEach((item) => {
            actions.forEach((citem) => {
              sendCommand(citem, item).then((res) => {
                count++
                if (count === actions.length) {
                  this.$message.success(res.msg)
                }
              })
            })
          })
        })
      },
      getPwmInfos(serialno, port) {
        const d = this.devicesObj[serialno].states['d' + port] + 's'
        const p = this.devicesObj[serialno].states['p' + port] + '%'
        return d + ' | ' + p
      },
      getDeviceImage(serialno, port) {
        const states = this.devicesObj[serialno].states
        const status = states.DO & Math.pow(2, port - 1) ? 'd_run' : 'd_close'
        return `${resourceBaseUrl}fm/${status}.png`
      },
      getValveClass(serialno, port) {
        const states = this.devicesObj[serialno].states
        const status = states.DO & Math.pow(2, port - 1)
        return status ? 'success' : 'info'
      },
      selectAll(cell) {
        this.childSelected = uniqueArr(this.childSelected.concat(cell.devices))
      },
      cancelAll(cell) {
        this.childSelected = this.childSelected.filter((val) => {
          return !cell.devices.includes(val)
        })
      },
      getSelectedValves(item) {
        return item.devices.filter((val) => {
          return this.childSelected.includes(val)
        }).length
      },
    },
  }
</script>

<style lang="scss" scoped>
  .collapse-title {
    align-items: center;
    width: 100%;
    b {
      min-width: 48px;
    }
  }
</style>
